<!DOCTYPE html>
<meta charset="utf-8"/>
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
    //注意token需要使用encodeURIComponent方法进行转义操作
    var token = encodeURIComponent('YeQwK8fnnXsTGd9k6DZuAGRR0rdOXqD3CHdvE6Naj/mZEot5L7hbPzmmD4CoksUl');
    var wsUri = "wss://127.0.0.1:9770?token=" + token;
    var output;
    let websocket;

    function init() {
        output = document.getElementById("output");
        testWebSocket();
    }

    function testWebSocket() {
        try {
            websocket = new WebSocket(wsUri);
            //websocket.binaryType = 'arraybuffer';
        } catch (e) {
            console.log(e);
            writeToScreen('<span style="color: red;">ERROR:</span> ' + e.message);
        }

        websocket.onopen = function (evt) {
            onOpen(evt)
        };
        websocket.onclose = function (evt) {
            onClose(evt)
        };
        websocket.onmessage = function (evt) {
            onMessage(evt)
        };
        websocket.onerror = function (evt) {
            onError(evt)
        };
    }

    function onOpen(evt) {
        writeToScreen("CONNECTED");
        // doSend("WebSocket rocks");
        let msg = JSON.stringify({
            "uri": "/liveapi/live_room/get_room_list",
            "data": {"uid": 1, "page": 0}
        });
        doSend(msg);
    }

    function onClose(evt) {
        writeToScreen("DISCONNECTED");
    }

    function onMessage(evt) {
        writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
        //websocket.close();
    }

    function onError(evt) {
        console.log('onError evt:' + JSON.stringify(evt));
        writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
    }

    function doSend(message) {
        writeToScreen("SENT: " + message);
        //var a = new Uint8Array([9]);
        //websocket.send(a.buffer);
        websocket.send(message);
    }

    function writeToScreen(message) {
        var pre = document.createElement("p");
        pre.style.wordWrap = "break-word";
        pre.innerHTML = message;
        output.appendChild(pre);
    }

    window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>